<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片区域 -->
        <el-card>
            <el-row>
                <el-button type="primary" @click="addDialogVisible = true" v-if="hasPermission('添加角色功能')">添加角色</el-button>
            </el-row>

            <!-- 角色列表区域 -->
            <el-table :data="rolelist" border stripe style="width: 100%; max-height: 600px; overflow-y: auto;">
                <el-table-column type="expand">
                    <template #default="scope">
                        <el-row v-for="(item1, i1) in getexpand" :key="item1.id" style="padding-left: 45px;" :class="[i1 !== getexpand.length - 1 ? 'bdbottom' : '', 'vcenter']">
                            <el-col :span="5">
                                <el-tag>{{ item1.authName }}</el-tag>
                                <el-icon class="e-icon-arrow-right"><CaretRight /></el-icon>
                            </el-col>
                            <el-col :span="19">
                                <el-row v-for="(item2, i2) in item1.children" :key="item2.id" :class="[i2 !== 0 ? 'bdtop' : '', 'vcenter']">
                                    <el-col :span="6">
                                        <el-tag type="success">{{ item2.authName }}</el-tag>
                                        <el-icon class="e-icon-arrow-right"><CaretRight /></el-icon>
                                    </el-col>
                                    <el-col :span="18">
                                        <template v-if="allRoleFunctions && allRoleFunctions.length > 0">
                                            <template v-for="roleFunc in allRoleFunctions" :key="roleFunc.role_id">
                                                <template v-if="roleFunc.role_id === scope.row.id && roleFunc.functions">
                                                    <template v-if="filterFunctionsByParent(roleFunc.functions, item2.authName).length > 0">
                                                        <el-tag type="warning" v-for="func in filterFunctionsByParent(roleFunc.functions, item2.authName)" :key="func" closable @close="() => removeRightById(func, scope.row.id)">{{ func }}</el-tag>
                                                    </template>
                                                    <template v-else>
                                                        <el-tag type="info">无该功能权限</el-tag>
                                                    </template>
                                                </template>
                                            </template>
                                        </template>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column prop="id" type="index" label="#" width="80"></el-table-column>
                <el-table-column prop="name" label="角色名称" width="200"></el-table-column>
                <el-table-column prop="description" label="角色描述"></el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <!-- {{ scope.row}} -->
                        <el-button type="primary" :icon="Edit" size="small"
                            @click="handleEdit(scope.row)" v-if="hasPermission('编辑角色功能')">编辑</el-button>
                        <el-button type="danger" :icon="Delete" size="small"
                            @click="handleDelete(scope.row.id)" v-if="hasPermission('删除角色功能')">删除</el-button>
                        <el-button type="warning" :icon="Setting" size="small"
                            @click="handleRole(scope.row)" v-if="hasPermission('分配权限功能')">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 修改角色的对话框 -->
            <el-dialog v-model="editDialogVisible" title="修改角色信息" width="50%" @close="editDialogClosed">
                <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="editForm.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDescription">
                        <el-input v-model="editForm.roleDescription"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="editDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="editRole">确定</el-button>
                    </span>
                </template>
            </el-dialog>
            <!-- 添加角色的对话框 -->
            <el-dialog v-model="addDialogVisible" title="添加角色" width="50%" @close="addDialogClosed">
                <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                    <el-form-item label="角色名称" prop="name">
                        <el-input v-model="addForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="description">
                        <el-input v-model="addForm.description"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="addDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="addRole">确定</el-button>
                    </span>
                </template>
            </el-dialog>
            <!-- 分配权限的对话框 -->
            <el-dialog v-model="roleDialogVisible" title="分配权限" width="50%" @close="roleDialogClosed">
                <p>当前的角色：{{ roleForm.name }}</p>
                <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all
                    :default-checked-keys="defKeys" ref="treeRef"></el-tree>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="roleDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="assignRights">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>
<script setup>
import { onMounted, ref } from "vue";
import { ArrowRight, CaretRight, Edit, Delete, Setting } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from "@/utils/http"

const rolelist = ref([])
const editDialogVisible = ref(false)
const roleDialogVisible = ref(false)
const editFormRef = ref()
const treeRef = ref()
const addDialogVisible = ref(false)
const addFormRef = ref()
const roleForm = ref({})
const rightsList = ref([])
const getexpand = ref([])
const defKeys = ref([])


const treeProps = {
    children: 'children',
    label: 'authName'
}
const addForm = ref({
    name: '',
    description: ''
})

const addFormRules = {
    name: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入角色描述', trigger: 'blur' }
    ]
}
const editForm = ref({
    id: '',
    roleName: '',
    roleDescription: ''
})

const editFormRules = {
    roleName: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    roleDescription: [
        { required: true, message: '请输入角色描述', trigger: 'blur' }
    ]
}
const addDialogClosed = () => {
    addFormRef.value.resetFields()
}

import qs from 'qs';

const addRole = () => {
    addFormRef.value.validate(async valid => {
        if (!valid) return;
        try {
            const { data: res } = await axios.post('/role/add/', qs.stringify(addForm.value), {
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            });
            if (res.code !== 200) throw new Error(res.message);
            ElMessage.success('添加角色成功！');
            addDialogVisible.value = false;
            getRolesList();
        } catch (error) {
            ElMessage.error(error.message);
        }
    });
}

const removeRightById = async (rightName, roleId) => {
    try {
        const result = await ElMessageBox.confirm(
            `确定要删除该角色的 "${rightName}" 权限吗?`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        if (result) {
            const { data: res } = await axios.delete(`/role/rights/${roleId}/${rightName}/`)
            
            if (res.code !== 200) {
                throw new Error(res.message || '删除权限失败')
            }
            ElMessage.success('删除权限成功！')
            // 只更新功能权限列表，不重新加载整个角色列表
            getAllRoleFunctions()
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error(error.message || '删除权限失败')
        }
    }
}

const getRolesList = async () => {
    const { data: res } = await axios.get('/roles/')
    console.log("res.data",res.data);
    if (res.code !== 200) return ElMessage.error(res.message)
    rolelist.value = res.data
    console.log("relelist", rolelist.value);
}



const getExpand = async() => {
    try {
        const { data: res } = await axios.get('/role/expand/')
        if (Array.isArray(res)) {
            getexpand.value = res
            console.log("权限数据：", getexpand.value)
        } else {
            ElMessage.error('获取权限数据失败')
        }
    } catch (error) {
        console.error('获取权限数据失败：', error)
        ElMessage.error('获取权限数据失败')
    }
}

const handleEdit = (row) => {
    editDialogVisible.value = true
    editForm.value = {
        id: row.id,
        roleName: row.name,
        roleDescription: row.description
    }
}

const editRole = () => {
    editFormRef.value.validate(async valid => {
        if (!valid) return
        const { data: res } = await axios.put(`/roles/${editForm.value.id}/`, {
            name: editForm.value.roleName,
            description: editForm.value.roleDescription
        })
        if (res.code !== 200) return ElMessage.error(res.message)
        ElMessage.success('修改角色信息成功！')
        editDialogVisible.value = false
        getRolesList()
    })
}

const handleDelete = (id) => {
    ElMessageBox.confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const { status } = await axios.delete(`/roles/${id}/`)
            if (status === 204) {
                ElMessage.success('删除角色成功！')
                getRolesList()
            } else {
                ElMessage.error('删除角色失败！')
            }
        } catch (error) {
            ElMessage.error(error.message || '删除角色失败！')
        }
    }).catch(() => {
        ElMessage.info('已取消删除')
    })
}
const getRightsList = async () => {
    const { data: res } = await axios.get('/rights/list/')
    if (res.code !== 200) return ElMessage.error(res.message)
    rightsList.value = res.data
}

const handleRole = async (row) => {
    roleForm.value = row
    rightsList.value = [

 {
            id: 1,
            authName: '用户管理',
            children: [
                {
                    id: 41,
                    authName: '用户列表',
                    children: [
                        { id: 411, authName: '添加用户功能' },
                        { id: 412, authName: '删除用户功能' },
                        { id: 413, authName: '修改用户功能' },
                        { id: 414, authName: '分配角色功能' }
                    ]
                }
            ]
        },
        {
            id: 2,
            authName: '权限管理',
            children: [
                {
                    id: 31,
                    authName: '角色列表',
                    children: [
                        { id: 311, authName: '添加角色功能' },
                        { id: 312, authName: '删除角色功能' },
                        { id: 313, authName: '编辑角色功能' },
                        { id: 314, authName: '分配权限功能' }
                    ]
                },
                hasPermission('查看权限') ? {
                    id: 32,
                    authName: '权限列表',
                    children: [
                        { id: 321, authName: '查看权限' }
                    ]
                } : null
            ].filter(item => item !== null)
        },
        {
            id:3,
            authName: '商品管理',
            children: [
                {
                    id: 11,
                    authName: '商品列表',
                    children: [
                        { id: 111, authName: '添加商品功能' },
                        { id: 112, authName: '修改商品功能' },
                        { id: 113, authName: '删除商品功能' }
                    ]
                },
                {
                    id: 12,
                    authName: '商品分类',
                    children: [
                        { id: 121, authName: '添加分类功能' },
                        { id: 122, authName: '编辑分类功能' },
                        { id: 123, authName: '删除分类功能' }
                    ]
                }
            ]
        },
        {
            id: 4,
            authName: '订单管理',
            children: [
                {
                    id: 21,
                    authName: '订单列表',
                    children: [
                        { id: 211, authName: '修改地址功能' },
                        { id: 212, authName: '商品发货功能' }
                    ]
                }
            ]
        },
       
        {
            id: 5,
            authName: '数据统计',
            children: [
                {
                    id: 51,
                    authName: '数据报表',
                    children: [
                        { id: 511, authName: '查看数据' }
                    ]
                }
            ]
        }
    ]

    try {
        // 调用新的后端接口获取角色已有的权限
        const { data: funcRes } = await axios.get(`/role/functions/${row.id}/`)
        if (funcRes.code === 200 && funcRes.data && funcRes.data.functions) {
            // 创建一个函数来根据权限名称查找对应的ID
            const findIdByAuthName = (tree, authName) => {
                for (const node of tree) {
                    if (node.authName === authName) {
                        return node.id
                    }
                    if (node.children && node.children.length > 0) {
                        const result = findIdByAuthName(node.children, authName)
                        if (result) return result
                    }
                }
                return null
            }

            // 将权限名称数组转换为权限ID数组
            const functionIds = funcRes.data.functions
                .map(authName => findIdByAuthName(rightsList.value, authName))
                .filter(id => id !== null)

            // 设置默认选中的节点
            defKeys.value = functionIds
        } else {
            defKeys.value = row.permissions || []
        }
    } catch (error) {
        console.error('获取角色功能失败:', error)
        ElMessage.warning('获取角色已有权限失败，将显示当前权限')
        defKeys.value = row.permissions || []
    }

    roleDialogVisible.value = true
    // 这里
    // getAllRoleFunctions()
}

const roleDialogClosed = () => {
    roleForm.value = {}
    defKeys.value = []
}

// 递归查找权限ID对应的权限名称
const findAuthNameById = (tree, id) => {
    for (const node of tree) {
        if (node.id === id) {
            return node.authName
        }
        if (node.children && node.children.length > 0) {
            const result = findAuthNameById(node.children, id)
            if (result) return result
        }
    }
    return null
}

const assignRights = async () => {
    // 获取所有选中和半选中的节点ID
    const rids = [...treeRef.value.getCheckedKeys(), ...treeRef.value.getHalfCheckedKeys()]

    // 构建权限ID和权限名称的映射
    const rightsMap = {}
    rids.forEach(id => {
        const authName = findAuthNameById(rightsList.value, id)
        if (authName) {
            rightsMap[id] = authName
        }
    })

    console.log("提交的数据：", rightsMap)

    // 提交到后端，包含ID和权限名称
    const { data: res } = await axios.put(`/role/rights/${roleForm.value.id}/`, {
        rids: rids.join(','),
        rightsMap: JSON.stringify(rightsMap) // 将权限映射转为JSON字符串
    })

    console.log("后端响应：", res)
    if (res.code !== 200) return ElMessage.error(res.message)
    ElMessage.success('分配权限成功！')
    roleDialogVisible.value = false
    getRolesList()
    getAllRoleFunctions()
}

const allRoleFunctions = ref([])

const hasPermission = (permission) => {
    try {
        const permissions = JSON.parse(sessionStorage.getItem('permissions') || '[]')
        // 确保permissions是数组
        const permissionArray = Array.isArray(permissions) ? permissions : [permissions]
        // 检查权限是否存在
        return permissionArray.some(p => p === permission || p.includes(permission))
    } catch (error) {
        console.error('权限检查失败:', error)
        return false
    }
}

const getAllRoleFunctions = async () => {
    try {
        const { data: res } = await axios.get('/role/functions/all/')
        if (res.code === 200) {
            allRoleFunctions.value = res.data
            console.log("所有角色的功能权限：", allRoleFunctions.value)
        } else {
            ElMessage.error('获取角色功能权限失败')
        }
    } catch (error) {
        console.error('获取角色功能权限失败：', error)
        ElMessage.error('获取角色功能权限失败')
    }
}

const filterFunctionsByParent = (functions, parentName) => {
    const menuFunctionMap = {
        '商品列表': ['添加商品功能', '修改商品功能', '删除商品功能'],
        '商品分类': ['添加分类功能', '编辑分类功能', '删除分类功能'],
        '订单列表': ['修改地址功能', '商品发货功能'],
        '角色列表': ['添加角色功能', '删除角色功能', '编辑角色功能', '分配权限功能'],
        '权限列表': ['查看权限'],
        '用户列表': ['添加用户功能', '删除用户功能', '修改用户功能', '分配角色功能'],
        '数据报表': ['查看数据']
    }
    
    // 获取当前二级菜单对应的权限列表
    const allowedFunctions = menuFunctionMap[parentName] || []
    
    // 过滤出属于当前二级菜单的权限
    return functions.filter(func => allowedFunctions.includes(func))
}

onMounted(() => {
    getRolesList()
    getExpand()
    getAllRoleFunctions()
})
</script>
<style scoped>
.el-tag {
    margin: 7px;
}

.bdtop {
    border-top: 1px solid #eee;
}

.bdbottom {
    border-bottom: 1px solid #eee;
}

.vcenter {
    display: flex;
    align-items: center;
}

.e-icon-arrow-right {
    margin-top: 30px !important;
}
</style>